package com.buvaka;

import com.mongodb.*;

import com.buvaka.features.LatLng;
import com.buvaka.features.LineString;

import org.bson.types.ObjectId;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;


/**
 * Created by ������� on 13.02.14.
 */
public class Link extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Get two objects and the style for linking
    	String obj1 = request.getParameter("Obj1");
        String obj2 = request.getParameter("Obj2");
        String style = request.getParameter("linkStyle");

        MongoClient client = new MongoClient();
        DB db = client.getDB("gis");
        DBCollection points = db.getCollection("points");
        DBCollection links = db.getCollection("links");
        
        //Get points from DB
        BasicDBObject query = new BasicDBObject("name", obj1);
        DBObject o1 = points.findOne(query);
        BasicDBObject query2 = new BasicDBObject("name", obj2);
        DBObject o2 = points.findOne(query2);
        
        //Make link
        LineString resultLine = new LineString(new LatLng[]{getLatLng(o1), (getLatLng(o2))});
   
        BasicDBObject insert = (BasicDBObject)com.mongodb.util.JSON.parse(resultLine.toString());
        //make the list of points to insert it into the link
        BasicDBList pointsNames = new BasicDBList();
        pointsNames.add(o1.get("name"));
        pointsNames.add(o2.get("name"));
        insert.append("pointsNames", pointsNames);
        //append lineStyle
        insert.append("style", style);
        
        links.insert(insert);

        UpdateGeoJsonFile.update(client);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    public LatLng getLatLng(DBObject in){
       //TODO: look aat this horror
        return new  LatLng(Double.parseDouble(((BasicDBList )((DBObject)in.get("geometry")).get("coordinates")).get(1).toString()), Double.parseDouble(((BasicDBList )((DBObject)in.get("geometry")).get("coordinates")).get(0).toString()));
    }
}
